package com.woniuxy.config;

import com.woniuxy.handler.LoginErrorHandler;
import com.woniuxy.handler.LoginSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private LoginSuccessHandler loginSuccessHandler;

    public UrlBasedCorsConfigurationSource getCorsFilter(){
        UrlBasedCorsConfigurationSource cfs = new UrlBasedCorsConfigurationSource();
        CorsConfiguration cors = new CorsConfiguration();
        cors.addAllowedHeader("*");
        cors.addAllowedOriginPattern("*");
        cors.addAllowedMethod("*");
        cors.setAllowCredentials(true);
        cfs.registerCorsConfiguration("/**",cors);
        return cfs;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭基础认证登录
        http.httpBasic().disable()
                //关闭跨站伪造拦截器
                .csrf().disable()
                //配置认证授权拦截规则
                .authorizeRequests()
                .antMatchers("/api/**","/loginfail","/login","/**").
                permitAll()
                .anyRequest().
                authenticated()
                .and()
                //进行账号密码登录认证
                .formLogin()
                //配置未登录跳转地址 因为前后端分离所有给到的返回值是一个结果集，填入接口
                //配置的未登録的跳轉地址（前後端分離，所以寫的是接口不是頁面）
                .loginPage("/loginFail")
                //配置登陸攔截的請求
                .loginProcessingUrl("/login")
                //登录成功之后的处理器
                .successHandler(loginSuccessHandler)
                .failureHandler(new LoginErrorHandler()).and()
                //开启跨域支持
                .cors().configurationSource(getCorsFilter());

    }

    @Bean
    public PasswordEncoder createPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


}